<template>
    <div class="service">
        <div class="con">
            <div class="title">
                <span v-if="id">商品编辑</span>
                <span v-else>商品发布</span>
            </div>

            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" label-position="top">
                <el-form-item label="服务类型" prop="cate2">
                    <el-row :gutter="20">
                        <el-col :span="5">
                            <el-select v-model="ruleForm.cate1" placeholder="请选择" @change="cate1change">
                                <el-option v-for="(item, index) in allcate" :key="index" :label="item.name"
                                    :value="index">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="5">
                            <el-select v-model="ruleForm.cate2" placeholder="请选择" @change="cate2change">
                                <el-option v-for="(item, index) in selectCate.two" :key="index" :label="item.name"
                                    :value="index">
                                </el-option>
                            </el-select>
                        </el-col>
                        <!-- <el-col :span="5">
                            <el-select v-model="ruleForm.cate3" placeholder="请选择">
                                <el-option v-for="(item, index) in cate3List" :key="index" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-col> -->
                    </el-row>
                </el-form-item>
                <el-form-item label="服务名称" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入服务名称"></el-input>
                </el-form-item>
                <el-form-item label="服务价格" prop="price">
                    <div class="flex-center-1 fwjg">
                        <div class="moeny-icon">￥</div>
                        <el-input v-model="ruleForm.price" :placeholder="demandText" :disabled="discussTrue">
                        </el-input>
                        <!-- <div class="tip" style="color: #e43c3c; cursor: pointer" @click="changeDiscuss">
                            {{ discussTrue ? "切换成价格" : "切换成面议" }}
                        </div> -->
                    </div>
                </el-form-item>
                <el-form-item label="商品封面（最多可上传5张）" prop="picList">
                    <el-upload :action="imgUploadUrl" list-type="picture-card" :on-remove="handleRemove"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="header"
                        :file-list="ruleForm.picList" :limit="5" :on-preview="handlePictureCardPreview"
                        accept=".jpg,.jpeg,.png">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="tip" style="margin-top: 9px">
                        仅支持png，jpg，jpeg格式，宽高比例为1:1（至少600*600px），大小5M内
                    </div>
                </el-form-item>
                <el-form-item label="服务详情">
                    <div class="flex-sb spfm">
                        <div>
                            <div class="label" style="padding-top: 0">
                                服务周期
                            </div>
                            <el-input v-model="ruleForm.service_time" placeholder="">
                            </el-input>
                            <div class="label">服务流程</div>
                            <el-input v-model="ruleForm.service_process" type="textarea" :rows="4" placeholder="">
                            </el-input>
                        </div>
                        <div>
                            <div class="label" style="padding-top: 0">
                                服务内容
                            </div>
                            <el-input v-model="ruleForm.service_content" placeholder="">
                            </el-input>
                            <div class="label">准备资料</div>
                            <el-input v-model="ruleForm.preparation" type="textarea" :rows="4" placeholder="">
                            </el-input>
                        </div>
                    </div>
                </el-form-item>
            </el-form>

            <div class="submit">
                <el-button type="primary" style="width: 166px; height: 50px" @click="submit">
                    <template v-if="id">编辑商品</template>
                    <template v-else>发布商品</template>
                </el-button>
            </div>
        </div>

        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import axios from "axios";

import {
    getallcate,
    add_shop,
    getShopDetail,
    shop_edit,
} from "@/assets/api/service";

export default {
    components: {},
    head() {
        return {
            title: "商品发布-【小竹财税平台】",
            meta: [
                {
                    hid: "keywords",
                    name: "keywords",
                    content: "小竹财税,服务商,小竹企服",
                },
            ],
        };
    },
    layout: "serverHome",
    data() {
        return {
            imgUploadUrl: "",

            ruleForm: {
                name: "",
                cate1: "",
                cate2: "",
                cate3: "",
                price: "",
                picList: [],
                service_time: "",
                service_process: "",
                service_content: "",
                preparation: "",
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入服务名称",
                        trigger: "blur",
                    },
                ],
                cate2: [
                    {
                        required: true,
                        message: "请选择服务类型",
                        trigger: "blur",
                    },
                ],
                picList: [
                    {
                        required: true,
                        message: "请上传商品图片",
                        trigger: "blur",
                    },
                ],
            },

            token: "",

            allcate: [],

            selectCate: {},
            cate2List: [],
            cate3List: [],

            id: null,

            demandText: "请输入服务价格",
            discussTrue: false,

            dialogImageUrl: "",
            dialogVisible: false,
        };
    },
    beforeDestroy() { },
    beforeMount() { },
    mounted() {
        this.token = localStorage.getItem("token");
        this.imgUploadUrl = axios.defaults.baseURL + "/api/common/upload";

        this.getallcate();
    },
    computed: {
        ...mapState("common", {
            userInfo: (state) => state.userInfo,
        }),
        header() {
            return {
                token: this.userInfo && this.token ? this.token : "",
            };
        },
    },
    watch: {},
    methods: {
        ...mapActions("common", ["getUserInfo2"]),
        //切换价格、面议
        //切换自定义价格
        changeDiscuss() {
            this.discussTrue = !this.discussTrue;
            if (this.discussTrue) {
                this.demandText = "面议";
                this.ruleForm.price = "面议";
            } else {
                this.demandText = "请输入服务价格";
                this.ruleForm.price = "";
            }
        },

        // 获取分类
        async getallcate() {
            const res = await getallcate({});
            if (res.code == 1) {
                this.allcate = res.data;
                let userinfo = await this.getUserInfo2();
                if (userinfo) {
                    // for (let item of this.allcate) {
                    //     if (item.id == userinfo.service_info.service_cate_id) {
                    //         this.selectCate = item;
                    //         this.ruleForm.cate1 = item.id;
                    //         if (this.$route.query.id) {
                    //             this.id = this.$route.query.id;
                    //         }
                    //         return;
                    //     }
                    // }

                    if (this.$route.query.id) {
                        this.id = this.$route.query.id;
                        this.getShopDetail();
                    }
                }
            }
        },

        // 编辑的初始数据
        async getShopDetail() {
            const res = await getShopDetail({
                id: this.id,
            });
            if (res.code == 1) {
                let shopInfo = res.data.info;
                this.ruleForm.cate3 = shopInfo.third_cate_id;
                this.ruleForm.name = shopInfo.name;
                this.ruleForm.price = shopInfo.price;
                this.ruleForm.service_time = shopInfo.service_time;
                this.ruleForm.service_process = shopInfo.service_process;
                this.ruleForm.service_content = shopInfo.service_content;
                this.ruleForm.preparation = shopInfo.preparation;

                for (let item of shopInfo.pic.split(",")) {
                    this.ruleForm.picList.push({
                        name: "",
                        url: item,
                    });
                }

                for (let i = 0; i < this.allcate.length; i++) {
                    let cate1 = this.allcate[i]
                    if (cate1.id == shopInfo.one_cate_id) {
                        this.ruleForm.cate1 = i
                        this.selectCate = cate1
                        for (let j = 0; j < cate1.two.length; j++) {
                            let cate2 = cate1.two[j]
                            if (cate2.id == shopInfo.two_cate_id) {
                                this.cate3List = cate2.third
                                this.ruleForm.cate2 = j
                                for (let ite of cate2.third) {
                                    if (ite.id == shopInfo.third_cate_id) {
                                        this.ruleForm.cate3 = ite.id;
                                        return
                                    }
                                }
                            }
                        }
                    }
                }
                // for (let i = 0; i < this.selectCate.two.length; i++) {
                //     // console.log(this.selectCate.two)
                //     if (this.selectCate.two[i].id == shopInfo.two_cate_id) {
                //         this.ruleForm.cate2 = i;
                //         this.cate3List = this.selectCate.two[i].third;
                //         break;
                //     }
                // }
            }
        },

        cate1change(i) {
            this.selectCate = this.allcate[i]
            this.cate3List = []
            this.ruleForm.cate3 = "";
            this.ruleForm.cate2 = "";
        },

        cate2change(index) {
            this.cate3List = this.selectCate.two[index].third;
            this.ruleForm.cate3 = "";
        },

        submit() {
            if (!this.ruleForm.service_time) {
                this.$message({
                    message: '请填写服务周期',
                    type: 'warning'
                });
                return
            }
            else if (!this.ruleForm.service_process) {
                this.$message({
                    message: '请填写服务流程',
                    type: 'warning'
                });
                return
            }
            else if (!this.ruleForm.service_content) {
                this.$message({
                    message: '请填写服务内容',
                    type: 'warning'
                });
                return
            }
            else if (!this.ruleForm.preparation) {
                this.$message({
                    message: '请填写准备资料',
                    type: 'warning'
                });
                return
            }
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.id) this.edit_shop();
                    else this.add_shop();
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

        async edit_shop() {
            let pic = [];
            for (let item of this.ruleForm.picList) {
                pic.push(item.url);
            }
            var price;
            if (this.ruleForm.price == "面议" || this.ruleForm.price == "") {
                price = 0;
            } else {
                price = this.ruleForm.price;
            }
            const res = await shop_edit({
                id: this.id,
                one_cate_id: this.allcate[this.ruleForm.cate1].id,
                two_cate_id: this.selectCate.two[this.ruleForm.cate2].id,
                // third_cate_id: this.ruleForm.cate3,
                name: this.ruleForm.name,
                price: price,
                service_time: this.ruleForm.service_time,
                service_process: this.ruleForm.service_process,
                service_content: this.ruleForm.service_content,
                preparation: this.ruleForm.preparation,
                pic: pic.join(","),
            });
            if (res.code == 1) {
                this.$message({
                    message: "修改成功",
                    type: "success",
                });
                setTimeout(() => {
                    // this.$router.go(-1);
                    this.$router.push({
                        path: "/service/servicecenter/goodsmanage",
                    });
                }, 2500);
            }
        },

        async add_shop() {
            let pic = [];
            for (let item of this.ruleForm.picList) {
                pic.push(item.url);
            }
            var price;
            if (this.ruleForm.price == "面议" || this.ruleForm.price == "") {
                price = 0;
            } else {
                price = this.ruleForm.price;
            }
            const res = await add_shop({
                one_cate_id: this.allcate[this.ruleForm.cate1].id,
                two_cate_id: this.selectCate.two[this.ruleForm.cate2].id,
                // third_cate_id: this.ruleForm.cate3,
                name: this.ruleForm.name,
                price: price,
                service_time: this.ruleForm.service_time,
                service_process: this.ruleForm.service_process,
                service_content: this.ruleForm.service_content,
                preparation: this.ruleForm.preparation,
                pic: pic.join(","),
            });
            if (res.code == 1) {
                this.$message({
                    message: "发布成功",
                    type: "success",
                });
                setTimeout(() => {
                    this.$router.push({
                        path: "/service/servicecenter/goodsmanage",
                    });
                }, 2500);
            }
        },

        // 上传成功钩子
        handleAvatarSuccess(res, file, fileList) {
            for (let item of fileList) {
                if (item.response) {
                    item.url = item.response.data.fullurl;
                }
            }
            this.ruleForm.picList = fileList;
            console.log(fileList);
        },

        // 移除上传文件钩子
        handleRemove(file, fileList) {
            for (let item of fileList) {
                if (item.response) {
                    item.url = item.response.data.fullurl;
                }
            }
            this.ruleForm.picList = fileList;
        },

        // 上传前检查
        beforeAvatarUpload(file) {
            const isType =
                file.type == "image/jpeg" ||
                file.type == "image/jpg" ||
                file.type == "image/png";
            const isLtMB = file.size / 1024 / 1024 < 5;

            if (!isType) {
                this.$message.error("上传头像图片只能是 JPG,JPEG,PNG 格式!");
            }
            if (!isLtMB) {
                this.$message.error("上传头像图片大小不能超过 5MB!");
            }
            return isType && isLtMB;
        },

        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
    },
};
</script>

<style lang="scss" scoped>
.con {
    width: 1200px;
    margin: 30px auto;
    padding-top: 40px;
    padding-left: 70px;
    padding-right: 184px;
    background-color: #ffffff;

    .title {
        font-size: 24px;
        font-weight: 600;
        color: #333333;
        margin-bottom: 60px;
    }
}

.fwjg {
    position: relative;

    .moeny-icon {
        position: absolute;
        left: 21px;
        z-index: 1;
    }

    &::v-deep .el-input__inner {
        padding-left: 47px;
    }

    .tip {
        margin-left: 22px;
        min-width: 447px;
    }
}

.tip {
    font-size: 14px;
    color: #999999;
}

.spfm {
    >div {
        width: 48%;

        .label {
            font-size: 14px;
            color: #333333;
            padding-top: 10px;
            padding-bottom: 13px;
            line-height: 1;
        }
    }
}

.submit {
    text-align: center;
    padding: 30px 0 60px 0;
}
</style>./productrelease.vue